package com.example.cinemasystemv2.controller;

import com.example.cinemasystemv2.entity.User;
import com.example.cinemasystemv2.service.UserService;
import com.example.cinemasystemv2.service.SystemLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import jakarta.servlet.http.HttpSession;
import java.util.Optional;

@Controller
@RequestMapping("/auth")
public class AuthController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private SystemLogService systemLogService;
    
    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }
    
    @PostMapping("/login")
    public String login(@RequestParam String username,
                       @RequestParam String password,
                       HttpSession session,
                       RedirectAttributes redirectAttributes) {
        try {
            User user = userService.authenticateUser(username, password);
            if (user != null) {
                session.setAttribute("username", user.getUsername());
                session.setAttribute("role", user.getRole());
                session.setAttribute("userId", user.getUserId());
                session.setAttribute("user", user);
                
                systemLogService.log("用户登录", username, "LOGIN");
                
                if (user.isMustChangePassword()) {
                    return "redirect:/auth/change-password";
                }
                
                // 根据用户角色跳转到对应的dashboard
                switch (user.getRole()) {
                    case "admin":
                        return "redirect:/admin/dashboard";
                    case "manager":
                        return "redirect:/manager/dashboard";
                    case "receptionist":
                        return "redirect:/receptionist/dashboard";
                    default:
                        return "redirect:/user/dashboard";
                }
            } else {
                redirectAttributes.addFlashAttribute("error", "用户名或密码错误");
                return "redirect:/login";
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "登录失败: " + e.getMessage());
            return "redirect:/login";
        }
    }
    
    @PostMapping("/register")
    public String register(@RequestParam String username,
                          @RequestParam String password,
                          @RequestParam String confirmPassword,
                          @RequestParam String phoneNumber,
                          RedirectAttributes redirectAttributes) {
        try {
            if (!password.equals(confirmPassword)) {
                redirectAttributes.addFlashAttribute("error", "两次输入的密码不一致");
                return "redirect:/register";
            }
            
            if (userService.existsByUsername(username)) {
                redirectAttributes.addFlashAttribute("error", "用户名已存在");
                return "redirect:/register";
            }
            
            systemLogService.log("用户注册", username, "REGISTER");
            
            redirectAttributes.addFlashAttribute("success", "注册成功，请登录");
            return "redirect:/login";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "注册失败: " + e.getMessage());
            return "redirect:/register";
        }
    }
    
    @GetMapping("/change-password")
    public String changePasswordPage(HttpSession session, Model model) {
        String username = (String) session.getAttribute("username");
        if (username == null) {
            return "redirect:/login";
        }
        
        Optional<User> userOpt = userService.getUserByUsername(username);
        if (userOpt.isPresent()) {
            model.addAttribute("mustChange", userOpt.get().isMustChangePassword());
        }
        
        return "change-password";
    }
    
    @PostMapping("/change-password")
    public String changePassword(@RequestParam String oldPassword,
                                @RequestParam String newPassword,
                                @RequestParam String confirmPassword,
                                HttpSession session,
                                RedirectAttributes redirectAttributes) {
        try {
            String username = (String) session.getAttribute("username");
            if (username == null) {
                return "redirect:/login";
            }
            
            if (!newPassword.equals(confirmPassword)) {
                redirectAttributes.addFlashAttribute("error", "两次输入的新密码不一致");
                return "redirect:/auth/change-password";
            }
            
            // 验证旧密码
            User user = userService.authenticateUser(username, oldPassword);
            if (user == null) {
                redirectAttributes.addFlashAttribute("error", "原密码错误");
                return "redirect:/auth/change-password";
            }
            
            userService.changePassword(username, newPassword);
            systemLogService.log("密码修改", username, "CHANGE_PASSWORD");
            
            // 根据用户角色跳转到对应的dashboard
            String role = (String) session.getAttribute("role");
            redirectAttributes.addFlashAttribute("success", "密码修改成功");
            switch (role) {
                case "admin":
                    return "redirect:/admin/dashboard";
                case "manager":
                    return "redirect:/manager/dashboard";
                case "receptionist":
                    return "redirect:/receptionist/dashboard";
                default:
                    return "redirect:/user/dashboard";
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "密码修改失败: " + e.getMessage());
            return "redirect:/auth/change-password";
        }
    }
    
    @GetMapping("/profile")
    public String profile(HttpSession session, Model model) {
        String username = (String) session.getAttribute("username");
        if (username == null) {
            return "redirect:/login";
        }
        
        Optional<User> userOpt = userService.getUserByUsername(username);
        if (userOpt.isPresent()) {
            model.addAttribute("user", userOpt.get());
        }
        
        return "profile";
    }
    
    @PostMapping("/update-profile")
    public String updateProfile(@RequestParam String phoneNumber,
                               HttpSession session,
                               RedirectAttributes redirectAttributes) {
        try {
            String username = (String) session.getAttribute("username");
            if (username == null) {
                return "redirect:/login";
            }
            
            Optional<User> userOpt = userService.getUserByUsername(username);
            if (userOpt.isPresent()) {
                User user = userOpt.get();
                user.setPhoneNumber(phoneNumber);
                userService.saveUser(user);
                
                systemLogService.log("个人信息更新", username, "UPDATE_PROFILE");
                redirectAttributes.addFlashAttribute("success", "个人信息更新成功");
            }
            
            return "redirect:/auth/profile";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "更新失败: " + e.getMessage());
            return "redirect:/auth/profile";
        }
    }
    
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        String username = (String) session.getAttribute("username");
        if (username != null) {
            systemLogService.log("用户退出登录", username, "LOGOUT");
        }
        session.invalidate();
        return "redirect:/login";
    }
}